<template>
  <div class="os-main">
    <ConfigForm v-model="dataForm" :config="config" ref="configFormRef" />

    <el-button type="primary" @click="openJson">查看表单数据</el-button>

    <el-drawer v-model="drawerVisiable" title="数据视图" :direction="'rtl'" size="40%">
      <CodeView :code-json="JSON.stringify(dataForm, null, '\t')"></CodeView>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import type { Config } from '@/components/ConfigForm'
import { ElButton, ElIcon } from 'element-plus';
import Demo2 from './components/Demo2.vue'
import { ref, markRaw } from 'vue';
import CodeView from '@/components/CodeView/index.vue'
import ConfigForm from '@/components/ConfigForm/index'

interface RestaurantItem {
  value: string
  link: string
}

/**ConfigForm绑定对象 */
const dataForm = ref<ObjectAny>({})


const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  cb(results)
}

const querySearchRemote = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value

  setTimeout(() => {
    cb(results)
  }, 1500 * Math.random())
}

const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
    )
  }
}

const loadAll = () => {
  return [
    { value: 'vue', link: 'https://github.com/vuejs/vue' },
    { value: 'element', link: 'https://github.com/ElemeFE/element' },
    { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
    { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
    { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
    { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
    { value: 'babel', link: 'https://github.com/babel/babel' },
  ]
}
const restaurants = ref<RestaurantItem[]>(loadAll())

const handleSelect = (item: RestaurantItem) => {
  console.log(item)
}

/**ConfigForm配置 */
const config = ref<Config>({
  mode: 'add',
  formProps: {},
  rowProps: {},
  columns: [
    { // 激活后列出建议
      prop: 'demo1', label: '激活后列出建议', type: 'autocomplete',
      props: { fetchSuggestions: querySearch, clearable: true },
      events: { select: handleSelect },
    },
    { prop: 'demo2', label: '自定义模板', type: 'custom', is: markRaw(Demo2) },
    { // 远程搜索
      prop: 'demo3', label: '远程搜索', type: 'autocomplete',
      props: { fetchSuggestions: querySearchRemote, clearable: true },
      events: { select: handleSelect }
    },
  ]
})


// 数据视图
const drawerVisiable = ref(false)
const openJson = () => {
  drawerVisiable.value = true
}
</script>